package com.parenting.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.parenting.entities.SystemUserDO;
import com.parenting.enums.ResultEnum;
import com.parenting.oauth2.config.AuthUtil;
import com.parenting.request.*;
import com.parenting.response.ShopUserResponse;
import com.parenting.response.SystemUserResponse;
import com.parenting.service.SystemUserService;
import com.parenting.util.TXSendSms;
import com.parenting.util.base.Result;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表信息 前端控制器
 * </p>
 *
 * @author 烟台业达-王世玺
 * @since 2021-08-11
 */
@RestController
@Api(tags = "店员管理接口", description = "提供店员的增删改查")
@RequestMapping("/user")
@Slf4j
public class SystemUserController {

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 新增 用户
     * @param user
     */
    @ApiOperation("新增店员信息接口")
    @PostMapping
    public  Result saveUser(@RequestBody ShopUserAddRequest user){

        return systemUserService.saveUser(user,AuthUtil.getUserInfo().getShopId());
    }

    /***
     * 修改用户信息
     * @param user
     */
    @ApiOperation("修改店员信息接口")
    @PutMapping
    public Result updateUser(@RequestBody ShopUserUpdateRequest user){
        systemUserService.updateUser(user);
        return Result.buildSuccess();
    }

    /***
     * 获得根据 店铺Id 与分页信息 获得 店员列表
     * @param userREQ
     */
    @ApiOperation("店员列表")
    @PostMapping("/search")
    public Result<IPage<ShopUserResponse>> findUserLisByShopId(@RequestBody ShopUserPageListRequest userREQ){
        userREQ.setShopId(AuthUtil.getUserInfo().getShopId());
        IPage<ShopUserResponse> userLisByShopId = systemUserService.findUserLisByShopId(userREQ);
        return Result.buildSuccess(userLisByShopId);
    }

    /***
     * 保存 用户与 按钮资源的关系
     * @param userId
     * @param resourcesIds
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户Id", required = true),
            @ApiImplicitParam(name = "resourcesIds", value = "资源Id集合", required = true,
                    allowMultiple = true, dataType = "String"),
    })
    @ApiOperation("新增店员资源关系数据接口")
    @PostMapping("save/res/{userId}")
    public  Result  saveUserAndResources(@PathVariable("userId") String userId, @RequestBody  List<String> resourcesIds){
        systemUserService.saveUserAndResources(userId,resourcesIds);
        return  Result.buildSuccess();
    }

    /***
     * 根据用户删除 用户信息
     * @param userId
     */
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    @ApiOperation("删除用户接口")
    @DeleteMapping("delete/{userId}")
    public Result  deleteUser(@PathVariable("userId") String userId){
        systemUserService.deleteUser(userId);
        return  Result.buildSuccess();
    }


    /**
     * 根据 用户 ID  查询 用户信息
     * @param userId
     * @return
     */
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true)
    @ApiOperation("根据用户userId号查询人员详细信息接口")
    @GetMapping("{userId}")
    public Result<SystemUserResponse> findUserByUserId(@PathVariable("userId")String userId){
        SystemUserDO byId = systemUserService.getById(userId);
        return  Result.ok(BeanUtil.copyProperties(byId,SystemUserResponse.class));
    }



    @ApiOperation("旧手机号发送验证码")
    @PostMapping("register/code/")
    public  Result registerUser(){
        SystemUserDO byId = systemUserService.getById(AuthUtil.getUserInfo().getId());
        String[] phones = {"+86 "+byId.getMobile()};
        String newCode= TXSendSms.getNewcode();
        log.info("===旧手机号发送验证码=== {}" ,newCode);
        stringRedisTemplate.opsForValue().set("user:phone:"+byId.getMobile(),newCode,60,TimeUnit.SECONDS);
        String[] code = {newCode};
        log.info("===旧手机号发送验证码数组=== {}" ,code);
        try {
            TXSendSms.sendSms("AKIDOMMbJaiLFwiwueDVcU1kALI0Z9zbjzSn", "LITvFKBoCL0ed9P4dEuQkgOxAAlT5RaV",
                    "1400488934", "沃养商户", "879807", phones, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return  Result.buildSuccess();
    }


    @ApiOperation("校验要旧手机号的验证码")
    @GetMapping("chek/old/{codeRequest}")
    public Result chekOldCode(@PathVariable("codeRequest") String codeRequest){
        log.info("===前台传过来的=== {}" ,codeRequest);
        SystemUserDO byId = systemUserService.getById(AuthUtil.getUserInfo().getId());
        String code = stringRedisTemplate.opsForValue().get("user:phone:" + byId.getMobile());
        log.info("==校验要旧手机号的验证码=缓存的== {}" ,code);
        if (codeRequest.equals(code)){
            return Result.buildSuccess("验证码正确!");
        }
        return Result.buildError(ResultEnum.CODE_ERROR.getMessage());
    }



    @ApiOperation("新手机号发送验证码")
    @PostMapping("code/new/{phone}")
    public  Result registerUser(@PathVariable("phone") String phone){
        String[] phones = {"+86 "+phone};
        String newCode= TXSendSms.getNewcode();
        log.info("===新手机号发送验证码=== {}" ,newCode);
        String key="user:Phone:"+phone;
        stringRedisTemplate.opsForValue().set(key,newCode, 60,TimeUnit.SECONDS);
        String[] code = {newCode};
        try {
            log.info("===新手机号发送验证码数组=== {}" ,code);
            TXSendSms.sendSms("AKIDOMMbJaiLFwiwueDVcU1kALI0Z9zbjzSn", "LITvFKBoCL0ed9P4dEuQkgOxAAlT5RaV",
                    "1400488934", "沃养商户", "879807", phones, code);
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        return  Result.buildSuccess();
    }


    @ApiOperation("修改手机号")
    @PostMapping("update/phone")
    public  Result updateUserPhone(@RequestBody UpdateUserPhone  updateUserPhone) {
        log.info("===前台传过来的=== {}" ,updateUserPhone);
        SystemUserDO byId = systemUserService.getById(AuthUtil.getUserInfo().getId());
        String key="user:Phone:"+updateUserPhone.getPhone();
        log.info("===key=== {}" ,key);
        String code = stringRedisTemplate.opsForValue().get(key);
        log.info("===缓存的== {}" ,code);
        if (updateUserPhone.getCode().equals(code)){
            byId.setMobile(updateUserPhone.getPhone());
            byId.setUpdateDate(new Date());
            systemUserService.updateById(byId);
            return Result.buildSuccess();
        }
        return Result.buildError(ResultEnum.CODE_ERROR.getMessage());
    }
}

